package com.jizi.config;

import com.jizi.pojo.SysUser;
import com.jizi.service.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author 宋朝阳
 * @create 2020 -11 -28 21:33
 */

//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserServiceImpl userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetauthorizationInfo");
        //SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        SysUser currentUser = (SysUser)subject.getPrincipal();   //拿到User对象

        //设置当前用户权限
        info.addStringPermission(currentUser.getPosition());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证doGetauthorizationInfo");

        //令牌
        UsernamePasswordToken userrToken = (UsernamePasswordToken) token;

        //从数据库中获取用户名，密码

        SysUser sysUser = userService.queryUser(userrToken.getUsername());

        if (sysUser==null){   //没有这个人
            return null;   //UnknownAccountException
        }

        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",sysUser);

        //可以加密： M5：21232F297A57A5A743894A0E4A801FC3            MD5盐值加密：21232F297A57A5A743894A0E4A801FC3username
        return new SimpleAuthenticationInfo(sysUser,sysUser.getPwd(),"");
    }
}
